package api

import (
	"encoding/json"
	// 	"fmt"
	"github.com/gin-gonic/gin"
	redis2 "github.com/gomodule/redigo/redis"
	"net/http"
	"news/global"
	"news/initialize"
	"news/models"
	"strconv"
)

type Category struct {
	ID   int32  `json:"id"`
	Name string `json:"name"`
}

type R struct {
	models.BaseModel
	Id         int      `json:"id"`
	Title      string   `json:"title"`
	CategoryId int      `gorm:"type:int" json:"category_id"`
	Category   Category `json:"category"`
}

// List 文章列表
func List(c *gin.Context) {
	limit := c.DefaultQuery("limit", "")
	key := c.DefaultQuery("key", "")
	id := c.DefaultQuery("category_id", "")

	limits, _ := strconv.Atoi(limit)
	var art []models.Article
	local := global.DB.Model(&models.Article{}).Preload("Category")
	//搜索昵称
	if key != "" {
		local = local.Where("title LIKE ?", "%"+key+"%")
	}

	cateGoryId, _ := strconv.Atoi(id)
	if limits == 0 {
		limits = 50
	}
	//搜索栏目
	if cateGoryId > 0 {
		local = local.Where("category_id = ?", cateGoryId)
	}

	local.Order("id desc").Select("id", "title", "category_id", "add_time", "update_time", "url").Limit(limits).Find(&art)

	c.JSON(
		http.StatusOK,
		gin.H{
			"code": http.StatusOK,
			"data": art,
		},
	)
}

// Detail 文章详情
func Detail(c *gin.Context) {
	Id := c.DefaultQuery("id", "")
	if Id == "" {
		c.JSON(http.StatusForbidden, gin.H{"data": "文章id不能为空"})
		return
	}
	var rs models.ArticleDetail
	if err := global.DB.Model(&models.ArticleDetail{}).Where("article_id = ?", Id).Preload("Article").First(&rs); err.RowsAffected == 0 {
		c.JSON(http.StatusForbidden, gin.H{"data": "文章不存在"})
		return
	}
	c.JSON(
		http.StatusOK,
		gin.H{
			"code": http.StatusOK,
			"data": rs,
		},
	)
}

// CateGory 获取文章栏目
func CateGory(c *gin.Context) {
	var cate1 *[]models.Category
	Redis := initialize.RedisConnect()
	cate, _ := redis2.String(Redis.Do("Get", global.WebsiteCate))
	_ = json.Unmarshal([]byte(cate), &cate1)
	c.JSON(
		http.StatusOK,
		gin.H{
			"code": http.StatusOK,
			"data": cate1,
		},
	)
}

// ArticleDel 文章删除
func ArticleDel(c *gin.Context) {
	id := c.DefaultQuery("id", "")
	if id == "" {
		c.JSON(http.StatusBadRequest, gin.H{"data": "文章id不能为空"})
		return
	}
	//删除主表
	if err := global.DB.Model(models.Article{}).Where("id = ? ", id).Delete(&models.Article{}); err.RowsAffected == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"data": "删除失败"})
		return
	}
	//删除副表
	if err := global.DB.Model(models.ArticleDetail{}).Where("article_id = ? ", id).Delete(&models.ArticleDetail{}); err.RowsAffected == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"data": "删除失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": "删除成功"})
}
